package com.jar.netty_demo.NIO.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 基于NIO实现的群聊
 * 1、基本属性初始化
 */
public class ServerChat {
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    public static final Integer PORT = 6667;

    /**
     * 初始化
     */
    public ServerChat() {
        try {
            //初始化ServerSocketChannel
            serverSocketChannel = ServerSocketChannel.open();
            //初始化Selector
            selector = Selector.open();
            //绑定端口
            serverSocketChannel.bind(new InetSocketAddress(PORT));
            //设置非阻塞
            serverSocketChannel.configureBlocking(false);
            //把ServerSocketChannel注册到Selector中
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听
     */
    public void listen() {
        try {
            while (true) {
                int count = selector.select(2000);
                //如果>0，表示有channel接入
                if (count > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()) {
                            SocketChannel sc = serverSocketChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "~已经连接");
                        } else if (selectionKey.isReadable()) {
                            SocketChannel sc = (SocketChannel) selectionKey.channel();
                            sc.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                            sc.configureBlocking(false);
                            //读取客户端的消息
                            readMessage(selectionKey);
                        }
                        iterator.remove();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取客户端消息
     */
    public void readMessage(SelectionKey selectionKey) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) selectionKey.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                String message = new String(buffer.array());
                System.out.println("收到来自客户端~" + channel.getRemoteAddress() + "的消息：" + message);
                //向其他客户端发送消息
                sendMessageToOther(message, channel);
            }
        } catch (Exception e) {
            try {
                if (channel != null) {
                    System.out.println(channel.getRemoteAddress() + "离线了。。。");
                    //取消注册
                    selectionKey.cancel();
                    //关闭 通道
                    channel.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 给其他客户端转发消息（不包含自己的）
     */
    public void sendMessageToOther(String message, SocketChannel self) {
        try {
            System.out.println("服务器转发消息：" + message);
            for (SelectionKey selectionKey : selector.keys()) {
                Channel targetChannel = selectionKey.channel();
                //排除自己
                if (targetChannel instanceof SocketChannel && targetChannel != self) {
                    SocketChannel dest = (SocketChannel) targetChannel;
                    ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                    dest.write(buffer);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //创建一个服务器对象
        ServerChat serverChat = new ServerChat();
        serverChat.listen();
    }
}
